package com.ken.fx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import okhttp3.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.websocket.Session;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public class BigModelNew extends WebSocketListener {
    public static final String hostUrl = "https://spark-api.xf-yun.com/v4.0/chat";
    public static final String appid = "b3491fbb";
    public static final String apiSecret = "ZjBmNWYzOGM3MzYwNTgxYjFiNjAwNTdl";
    public static final String apiKey = "fc137a39a8b8409a4e3a5ece49c88029";

    public static ConcurrentHashMap<String, List<RoleContent>> userHistoryMap = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String, String> userAnswers = new ConcurrentHashMap<>();
    public static String NewQuestion = "";
    public static final Gson gson = new Gson();
    private String userId;
    private Boolean wsCloseFlag;
    private static Session session;
    private static Boolean totalFlag = true;
    private boolean sendEndFlag = false; // 标志用于控制是否发送结束标识

    public BigModelNew(String userId, Boolean wsCloseFlag) {
        this.userId = userId;
        this.wsCloseFlag = wsCloseFlag;
        userHistoryMap.putIfAbsent(userId, new CopyOnWriteArrayList<>());
        userAnswers.putIfAbsent(userId, "");
    }

    public static void main(String[] args) throws Exception {
        while (true) {
            if (totalFlag) {
                Scanner scanner = new Scanner(System.in);
                System.out.print("我：");
                totalFlag = false;
                NewQuestion = scanner.nextLine();
                String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
                OkHttpClient client = new OkHttpClient.Builder().build();
                String url = authUrl.replace("http://", "ws://").replace("https://", "wss://");
                Request request = new Request.Builder().url(url).build();
                for (int i = 0; i < 1; i++) {
                    String userId = UUID.randomUUID().toString();
                    userAnswers.put(userId, "");
                    //System.out.println("用户：" + userId);
                    WebSocket webSocket = client.newWebSocket(request, new BigModelNew(userId, false));
                }
            } else {
                Thread.sleep(200);
            }
        }
    }

    public void startWork(Session session, String newQuestion) throws Exception {
        setNewQuestion(newQuestion);
        setSession(session);
        if (totalFlag) {
            System.out.println("我：" + NewQuestion);
            totalFlag = false;
            String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
            OkHttpClient client = new OkHttpClient.Builder().build();
            String url = authUrl.replace("http://", "ws://").replace("https://", "wss://");
            Request request = new Request.Builder().url(url).build();
            userAnswers.put(userId, "");
            System.out.println(userId);
            System.out.println(userHistoryMap.get(userId));
            WebSocket webSocket = client.newWebSocket(request, new BigModelNew(userId, wsCloseFlag));
        } else {
            Thread.sleep(200);
        }
    }

    public boolean canAddHistory(String userId) {
        List<RoleContent> historyList = userHistoryMap.get(userId);
        int historyLength = historyList.stream().mapToInt(roleContent -> roleContent.content.length()).sum();
        if (historyLength > 12000) {
            historyList.subList(0, Math.min(5, historyList.size())).clear();
            return false;
        }
        return true;
    }

    class MyThread extends Thread {
        private WebSocket webSocket;
        private String userId;

        public MyThread(WebSocket webSocket, String userId) {
            this.webSocket = webSocket;
            this.userId = userId;
        }

        public void run() {
            try {
                JSONObject requestJson = new JSONObject();

                JSONObject header = new JSONObject();
                header.put("app_id", appid);
                header.put("uid", UUID.randomUUID().toString().substring(0, 10));

                JSONObject parameter = new JSONObject();
                JSONObject chat = new JSONObject();
                chat.put("domain", "4.0Ultra");
                chat.put("temperature", 0.5);
                chat.put("max_tokens", 4096);
                parameter.put("chat", chat);

                JSONObject payload = new JSONObject();
                JSONObject message = new JSONObject();
                JSONArray text = new JSONArray();

                List<RoleContent> historyList = userHistoryMap.get(userId);
                if (!historyList.isEmpty()) {
                    historyList.forEach(tempRoleContent -> text.add(JSON.toJSON(tempRoleContent)));
                }

                RoleContent roleContent = new RoleContent();
                roleContent.role = "user";
                roleContent.content = NewQuestion;
                text.add(JSON.toJSON(roleContent));
                historyList.add(roleContent);

                message.put("text", text);
                payload.put("message", message);

                requestJson.put("header", header);
                requestJson.put("parameter", parameter);
                requestJson.put("payload", payload);

                webSocket.send(requestJson.toString());

                while (true) {
                    Thread.sleep(200);
                    if (wsCloseFlag) {
                        break;
                    }
                }
                webSocket.close(1000, "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
        System.out.print("大模型：");
        MyThread myThread = new MyThread(webSocket, userId);
        myThread.start();
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
        if (myJsonParse.header.code != 0) {
            System.out.println("发生错误，错误码为：" + myJsonParse.header.code);
            System.out.println("本次请求的sid为：" + myJsonParse.header.sid);
            webSocket.close(1000, "");
        }
        List<Text> textList = myJsonParse.payload.choices.text;
        String totalAnswer = userAnswers.get(userId);
        String answer="";
        for (Text temp : textList) {
            System.out.print(temp.content);
            totalAnswer += temp.content;
            answer+=temp.content;
//            sendMessage(temp.content);
        }
        //System.out.println(answer);
        sendMessage(answer);
        //userAnswers.put(userId, totalAnswer);
        if (myJsonParse.header.status == 2) {
            //sendMessage("#");
            System.out.println();
            System.out.println("*************************************************************************************");
            if (canAddHistory(userId)) {
                RoleContent roleContent = new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(totalAnswer);
                userHistoryMap.get(userId).add(roleContent);
            } else {
                userHistoryMap.get(userId).remove(0);
                RoleContent roleContent = new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(totalAnswer);
                userHistoryMap.get(userId).add(roleContent);
            }
            wsCloseFlag = true;
            totalFlag = true;
            webSocket.close(1000, "");
            sendMessage("#");
        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        try {
            if (response != null) {
                int code = response.code();
                System.out.println("onFailure code:" + code);
                System.out.println("onFailure body:" + response.body().string());
                if (code != 101) {
                    System.out.println("connection failed");
                    System.exit(0);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void clearUserHistory(String userId) {
        userHistoryMap.remove(userId);
        userAnswers.remove(userId);
        System.out.println("用户历史记录已清除：" + userId);
    }

    public void setNewQuestion(String newQuestion) {
        NewQuestion = newQuestion;
    }

    public void setSession(Session session) {
        BigModelNew.session = session;
    }

    private synchronized void sendMessage(String message) {
        session.getAsyncRemote().sendText(message);
    }

    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);

        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath()))
                .newBuilder()
                .addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)))
                .addQueryParameter("date", date)
                .addQueryParameter("host", url.getHost())
                .build();

        return httpUrl.toString();
    }

    class JsonParse {
        Header header;
        Payload payload;
    }

    class Header {
        int code;
        int status;
        String sid;
    }

    class Payload {
        Choices choices;
    }

    class Choices {
        List<Text> text;
    }

    class Text {
        String role;
        String content;
    }

    class RoleContent {
        String role;
        String content;

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
}
